package com.sample.app;

import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.StatelessSession;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
import org.drools.compiler.PackageBuilderErrors;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class DroolsHelper {
    private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(DroolsHelper.class);
    private static final String DRL_FILE = "/drl/rule.drl";

    private RuleBase rbase;
    private PackageBuilder pbuilder;

    /**
     * //1. Read the DRL File and add to package builder
     * //2. Check for any errors
     * //3. Add package to rule base
     */

    protected void initialiseDrools() {
        rbase = RuleBaseFactory.newRuleBase();
        pbuilder = new PackageBuilder();

        try {
            Reader reader = new InputStreamReader(DroolsHelper.class.getResourceAsStream(DRL_FILE));
            pbuilder.addPackageFromDrl(reader);
        } catch (DroolsParserException ex) {
            LOGGER.error(ex.getMessage());
        } catch (IOException ex) {
            LOGGER.error(ex.getMessage());
        }

        PackageBuilderErrors errors = pbuilder.getErrors();

        if (errors.getErrors().length > 0) {
            for (int i = 0; i < errors.getErrors().length; i++) {
                LOGGER.error(errors.getErrors()[i]);
            }
            throw new IllegalArgumentException("Could not parse knowledge.");
        }

        try {
            rbase.addPackage(pbuilder.getPackage());
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }


    public Triangle initializeTriangle(int a, int b, int c) {
        Triangle triangle = new Triangle(a, b, c);
        StatelessSession sessionObject = getSessionObject();
        sessionObject.execute(triangle);
        return triangle;
    }

    protected StatelessSession getSessionObject() {
        if (rbase == null) {
            initialiseDrools();
        }
        return rbase.newStatelessSession();
    }
}
